<?php
/**
 * 系统设置
 * @since 1.0 <2015-5-26> SoChishun <14507247@qq.com> Added.
 */
include 'function.php';
$config = load_config();
if (!$config || !isset($config['db_object_dir'])) {
    die('资源文件目录不存在!');
}
session_start();
if (isset($_SESSION['dbconfig'])) {
    $dbconfig = $_SESSION['dbconfig'];
    if (!$dbconfig) {
        exit('操作超时!');
    }
} else {
    if (!I('db_name')) {
        exit('数据库配置无效!');
    }
    $dbconfig = $_POST;
    $_SESSION['dbconfig'] = $dbconfig;
}
$subdir = $config['db_object_dir'];
if ('create' == query('action')) {
    die(json_encode(create_table()));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>系统设置-INSTALL</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="//libs.useso.com/js/yui/3.17.2/cssreset/cssreset-min.css" rel="stylesheet" />
        <link href="./Skin/theme-blue.css" rel="stylesheet" />
        <script src="//libs.useso.com/js/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>   
    </head>
    <body class="page-step-setting">
        <div class="header">
            <div class="frame-style">
                <div class="logo"><?php echo $config['APP_NAME'] ?> INSTALL安装向导</div>
                <div class="breadcrumb">
                    <ul>
                        <li><a href="./install.php">欢迎界面</a></li>
                        <li><a href="./step_env.php">环境检测</a></li>
                        <li><a href="./step_db_setting.php">系统配置</a></li>
                        <li class="cur">初始化数据</li>
                        <li>完成安装</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="bodier">
            <fieldset>
                <h3>安装数据库</h3>
                <div style="max-height:420px; width:800px; overflow-y: auto;">
                    <table id="creating-tables-status" class="table-grid" cellspacing="0">
                        <tr><th>安装项目</th><th class="al-right">安装进度</th></tr>
                        <?php
                        $i = 1;
                        // 支持三级子目录遍历 2015-7-17 SoChishun Added.
                        foreach ($subdir as $dir) {
                            if (!file_exists($dir)) {
                                echo '<tr><td colspan="2">', $dir, ' 不存在!</td></tr>';
                                continue;
                            }
                            $odir = opendir($dir);
                            while (false !== ($file = readdir($odir))) {
                                if ('.' == $file || '..' == $file) {
                                    continue;
                                }
                                $filename = str_replace('//', '/', $dir . '/' . $file);
                                if (!is_dir($filename)) {
                                    if (strpos($file, '.sql')) {
                                        echo '<tr id="dbo_' . $i . '" title="' . $filename . '"><td class="table">' . $i . '.' . $file . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                        $i++;
                                    }
                                    continue;
                                }
                                $odir2 = opendir($filename);
                                while (false !== ($file2 = readdir($odir2))) {
                                    if ('.' == $file2 || '..' == $file2) {
                                        continue;
                                    }
                                    $filename2 = str_replace('//', '/', $filename . '/' . $file2);
                                    if (!is_dir($filename2)) {
                                        if (strpos($file2, '.sql')) {
                                            echo '<tr id="dbo_' . $i . '" title="' . $filename2 . '"><td class="table">' . $i . '.' . $file2 . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                            $i++;
                                        }
                                        continue;
                                    }
                                    $odir3 = opendir($filename2);
                                    while (false !== ($file3 = readdir($odir3))) {
                                        if ('.' == $file3 || '..' == $file3) {
                                            continue;
                                        }
                                        $filename3 = str_replace('//', '/', $filename2 . '/' . $file3);
                                        if (!is_dir($filename3)) {
                                            if (strpos($file3, '.sql')) {
                                                echo '<tr id="dbo_' . $i . '" title="' . $filename3 . '"><td class="table">' . $i . '.' . $file3 . '</td><td class="status break-line al-right"><span class="orange">待安装</span></td></tr>';
                                                $i++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        ?>
                    </table>
                </div>
                <div class="footer">
                    <a href="./step_db_setting.php">上一步</a>            
                    <a href="#" id="lnk-start">立即安装</a>
                    <a href="./step_data.php" style="display:none">下一步</a>
                </div>
            </fieldset>
            <form style="display:none;" id="frmDb">
                <input type="text" name="db_host" value="<?php echo $dbconfig['db_host'] ?>" />
                <input type="text" name="db_name" value="<?php echo $dbconfig['db_name'] ?>" />  
                <input type="text" name="db_user" value="<?php echo $dbconfig['db_user'] ?>" />
                <input type="password" name="db_pwd" value="<?php echo $dbconfig['db_pwd'] ?>" />
                <input type="text" name="db_prefix" value="<?php echo $dbconfig['db_prefix'] ?>" />
            </form>
        </div>
        <script type="text/javascript">
            // 2015-5-26 SoChishun Added.
            $('#lnk-start').click(function () {
                create_tables();
                $(this).hide().next().show();
                return false;
            })
            function create_tables() {
                var params = $('#frmDb').serialize();
                var url = 'step_db_install.php';
                $('#creating-tables-status tr[id]').each(function (i) {
                    var $tr = $(this);
                    var arg = '&action=create&id=' + $tr.attr('id') + '&path=' + $tr.attr('title');
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: params + arg,
                        dataType: 'json',
                        success: function (msg) {
                            if (msg.status) {
                                $('#' + msg.id).find('.status').html('<span class="ok">已安装</span>');
                            } else {
                                $('#' + msg.id).find('.status').html('<div class="red">安装失败 <a href="#" onclick="$(this).next().toggle();return false;">[消息]</a><div style="display:none;">' + msg.info + '</div></div>');
                            }
                        },
                        beforeSend: function () {
                            $tr.find('.status').html('<span class="orange">安装中...</span>');
                        }
                    })
                });
            }
        </script>
    </body>
</html>
<?php

// 获取post数据
function query($name) {
    return isset($_POST[$name]) ? $_POST[$name] : '';
}

function create_table() {
    $id = query('id');
    $path = query('path');
    if (!is_file($path)) {
        return array('status' => false, 'id' => $id, 'info' => $path . ' 不存在');
    }
    $sqls = load_sql_file($path);
    // $sql = file_get_contents($path);
    if (!$sqls) {
        return array('status' => false, 'id' => $id, 'info' => $path . ' 无内容');
    }
    $config = array('db_host' => query('db_host'), 'db_name' => query('db_name'), 'db_user' => query('db_user'), 'db_pwd' => query('db_pwd'), 'db_prefix' => query('db_prefix'));
    $link = @mysql_connect($config['db_host'], $config['db_user'], $config['db_pwd']);
    if (false === $link) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_query('CREATE DATABASE IF NOT EXISTS ' . $config['db_name'] . ' DEFAULT CHARSET utf8 COLLATE utf8_general_ci;');
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_select_db($config['db_name']);
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    $res = @mysql_query('SET NAMES UTF8');
    if (false === $res) {
        return array('status' => false, 'id' => $id, 'info' => mysql_error());
    }
    foreach ($sqls as $sql) {
        $res = @mysql_query($sql);
        if (false === $res) {
            return array('status' => false, 'id' => $id, 'info' => mysql_error());
        }
    }
    $_SESSION['suinstall-db-config'] = $config;
    return array('status' => true, 'id' => $id, 'info' => $id);
}

/**
 * 加载sql文件为分号分割的数组
 * 支持存储过程和函数提取，自动过滤注释
 * @param string $path 文件路径
 * @return boolean|array
 * @since 1.0 <2015-5-27> SoChishun Added.
 */
function load_sql_file($path, $fn_splitor = ';;') {
    if (!file_exists($path)) {
        return false;
    }
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $arr = false;
    $str = '';
    $skip = false;
    $fn = false;
    foreach ($lines as $line) {
        $line = trim($line);
        // 过滤注释
        if (!$line || 0 === strpos($line, '--') || 0 === strpos('*') || 0 === strpos($line, '/*') || (false !== strpos($line, '*/') && strlen($line) == (strpos($line, '*/') + 2))) {
            if (!$skip && 0 === strpos($line, '/*')) {
                $skip = true;
            }
            if ($skip && false !== strpos($line, '*/') && strlen($line) == (strpos($line, '*/') + 2)) {
                $skip = false;
            }
            continue;
        }
        if ($skip) {
            continue;
        }
        // 提取存储过程和函数
        if (0 === strpos($line, 'DELIMITER ' . $fn_splitor)) {
            $fn = true;
            continue;
        }
        if (0 === strpos($line, 'DELIMITER ;')) {
            $fn = false;
            $arr[] = $str;
            $str = '';
            continue;
        }
        if ($fn) {
            $str.=$line . ' ';
            continue;
        }
        // 提取普通语句
        $str.=$line;
        if (false !== strpos($line, ';') && strlen($line) == (strpos($line, ';') + 1)) {
            $arr[] = $str;
            $str = '';
        }
    }
    return $arr;
}
?>
    